package com.umeox.auto_update

import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.view.View
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.TextView
import com.umeox.auto_update.AutoUpdateDeviceProxy.Companion.STATE_ERROR
import com.umeox.auto_update.AutoUpdateDeviceProxy.Companion.STATE_RUN
import com.umeox.auto_update.AutoUpdateDeviceProxy.Companion.STATE_SUCCESS
import com.umeox.base.BaseRecyclerViewAdapter
import com.umeox.base.BaseViewHolder

class DeviceInfoListAdapter : BaseRecyclerViewAdapter<AutoUpdateDeviceProxy>() {

    private val deviceList = mutableListOf<AutoUpdateDeviceProxy>()

    fun refreshData(list: MutableList<AutoUpdateDeviceProxy>) {
        deviceList.clear()
        deviceList.addAll(list)
        notifyDataSetChanged()
    }

    override fun getLayoutId(viewType: Int): Int = R.layout.item_device_info

    override fun getDataByPosition(position: Int): AutoUpdateDeviceProxy = deviceList[position]

    override fun getTotalSize(): Int = deviceList.size

    override fun convert(holder: BaseViewHolder, data: AutoUpdateDeviceProxy, position: Int) {
        holder.getView<TextView>(R.id.item_name).text = data.device.name
        holder.getView<TextView>(R.id.item_mac).text = data.device.mac
        (holder.getView<LinearLayout>(R.id.item).background as GradientDrawable).setColor(
            getStateColor(data)
        )
        if (data.state == STATE_RUN) {
            holder.getView<ProgressBar>(R.id.item_pb).visibility = View.VISIBLE
        } else {
            holder.getView<ProgressBar>(R.id.item_pb).visibility = View.GONE
        }
    }

    private fun getStateColor(data: AutoUpdateDeviceProxy): Int {
        return when (data.state) {
            STATE_ERROR -> {
                Color.RED
            }
            STATE_SUCCESS -> {
                Color.GREEN
            }
            else -> {
                Color.WHITE
            }
        }
    }
}